import Taro from "@tarojs/taro";
const white_res_code = [200, 10001, 10002];
const white_uri = ["/auth/login"];
import { loginByCode } from "../api/user";
function getTokenByApi() {
  return new Promise((resolve) => {
    Taro.login({
      success: (res) => {
        loginByCode(res.code).then((res) => {
          resolve(res["token"]);
        });
      },
    });
  });
}
async function request(url, data, method): Promise<any> {
  let notNeedTokenflag =
    white_uri.filter((item) => url.includes(item)).length > 0;
  let token = Taro.getStorageSync("token");
  if (!notNeedTokenflag && (!token || token === "")) {
    token = await getTokenByApi();
    Taro.setStorageSync("token", token);
  }
  const header = {
    "content-type": "application/json",
  };
  if (!notNeedTokenflag) {
    header["Authorization"] = `Bearer ${token}`;
  }
  return new Promise((resolve) => {
    let retryCount = Taro.getStorageSync("returCount") || 0;
    if (retryCount >= 10) {
      setTimeout(() => {
        Taro.removeStorageSync("returCount");
      }, 5000);
      return Taro.showToast({
        title: "您已被限制5秒内不可以访问接口",
        icon: "none",
      });
    }
    Taro.request({
      url,
      data,
      method,
      header,
    })
      .then((res) => {
        if (res.statusCode === 200) {
          const backEndRes = res.data;
          const resCode = backEndRes.code;
          if (!white_res_code.includes(resCode)) {
            switch (resCode) {
              case 500:
                return Taro.showToast({
                  title: "请求失败,系统异常:" + backEndRes.msg,
                  icon: "none",
                });
              case 401:
                Taro.removeStorageSync("token");
                Taro.setStorageSync("returCount", retryCount + 1);
                request(url, data, method);
                return Taro.showToast({
                  title: "请求失败,请您登陆:" + backEndRes.msg,
                  icon: "none",
                });
              case 403:
                Taro.removeStorageSync("token");
                Taro.setStorageSync("returCount", retryCount + 1);
                request(url, data, method);
                return Taro.showToast({
                  title: "请求失败,暂无权限:" + backEndRes.msg,
                  icon: "none",
                });

              default:
                return Taro.showToast({
                  title: "请求失败:" + res.data.error,
                  icon: "none",
                });
            }
          } else {
            resolve(backEndRes.data);
          }
          resolve(res.data);
        } else {
          Taro.showToast({ title: "请求失败:" + res.data.error, icon: "none" });
        }
      })
      .catch((err) => {
        Taro.showToast({ title: "网络错误,提示:" + err.errMsg, icon: "none" });
      });
  });
}
function get(url) {
  return request(url, null, "GET");
}

function post(url, data) {
  return request(url, data, "POST");
}
function del(url) {
  return request(url, null, "DELETE");
}
function put(url, data) {
  return request(url, data, "POST");
}
export { get, post, del, put };
